package day015.algorithm;

public class BinarySearchDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println(binarySearch(arr, 8));
    }

    public static int binarySearch(int[] arr, int key) {
        int max = arr.length - 1;
        int min = 0;

        while (min <= max) {
            int mid = (max + min) / 2;

            if ((arr[mid] == key)) {
                return mid;
            } else if (arr[mid] < key) {
                min = mid + 1;
            } else if (arr[mid] > key) {
                max = mid - 1;
            }
        }

        return -1;
    }
}
